<template>
  <div class="add-category">
    <el-dialog title="新增分类" :visible.sync="addCategorySync" :before-close="handleCloseDialog" width="50%">
      <el-card shadow="never">
        <div class="add-category-body">
          <el-form label-width="100px" :model="addCategoryParam"  ref="addCategoryFrom" :rules="addCategoryRules">
            <el-form-item label="分类代码:" prop="categoryCode" >
              <el-input  v-model="addCategoryParam.categoryCode" class="add-category-input" clearable maxlength="7"></el-input>
            </el-form-item>
            <el-form-item label="分类名称:" prop="categoryName">
              <el-input   v-model="addCategoryParam.categoryName"  class="add-category-input" clearable></el-input>
            </el-form-item>
            <el-form-item label="分类级别:" prop="categoryLevel">
              <el-radio v-model=radio label='0'>一级分类</el-radio>
              <el-radio v-model=radio label='1' @change="handleGetCategoryParent">二级分类</el-radio>
              <el-radio v-model=radio label='2' @change="handleGetCategoryParent">三级分类</el-radio>
            </el-form-item>
            <el-form-item label="父级分类:" prop="categoryParent" v-show="radio!=='0'" >
              <el-select placeholder="请选择父级分类" class="add-category-input" filterable clearable  v-model="addCategoryParam.categoryParent">
                <el-option v-for="item in categoryParentData" :key="item.id" :value="item.id" :label="(item.categoryCode)+' '+(item.categoryName)">{{item.categoryCode}} {{item.categoryName}}</el-option>
              </el-select>
            </el-form-item>
            <el-form-item label="分类备注:" prop="categoryRemark">
              <el-input  type="textarea" maxlength="200" show-word-limit class="add-category-input" clearabl  v-model="addCategoryParam.categoryRemark"></el-input>
            </el-form-item>
          </el-form>
        </div>
      </el-card>
      <div class="dialog-footer">
        <el-button @click="handleCloseDialog">取 消</el-button>
        <el-button type="primary" @click="handleAddCategory(false)">确认添加</el-button>
        <el-button type="success" @click="handleAddCategory(true)">保存并再次添加</el-button>
      </div>
    </el-dialog>
  </div>

</template>
<script>
import { AddCategoryApi, GetCategoryParentApi } from '@/request/category/category-api'
import { mapState } from 'vuex'
import store from '@/store'
export  default {
  computed : {
    ...mapState({
      addCategorySync:state => state.CategoryEdit.addCategorySync
    })
  },
  data(){
    return{
      sync:true,
      radio:'0',
      categoryParentData:[],
      addCategoryParam:{
        categoryCode:null,
        categoryName: null,
        categoryLevel: 0,
        categoryParent:null,
        categoryRemark:null
      },
      addCategoryRules:{
        categoryCode: { required: true, message: '请输入分类代码', trigger: 'blur' },
        categoryName: { required: true, message: '请输入分类名', trigger: 'blur' },
        categoryLevel: { required: true, message: '请选择分类级别', trigger: 'blur' }
      }
    }
  },
  methods:{
    resetFrom(){
      //更新初始数据
      this.radio = '0'
      this.categoryParentData = []
      this.addCategoryParam = {
        categoryCode: null,
        categoryName: null,
        categoryLevel: 0,
        categoryParent: null,
        categoryRemark: null
      }
      //取消单项验证
      this.$nextTick(() => {
        this.$refs['addCategoryFrom'].clearValidate()
      })
    },
    close(){
     this.resetFrom()
      store.commit('CategoryEdit/changeAddCategorySync', false)
    },
    handleCloseDialog () {
      this.$confirm('确定取消添加分类吗？', '提示', {
        'confirmButtonText': '确定',
        'cancelButtonText': '取消',
        'type': 'info'
      }).then(() => {
        this.close()
      }).catch((e) => {
        if (e === 'cancel') {
        }
      })
    },
     async handleGetCategoryParent () {
      this.addCategoryParam.categoryLevel=parseInt(this.radio)
       this.categoryParentData = []
       this.addCategoryParam.categoryParent=null
       let res = await GetCategoryParentApi(this.radio)
       if (res.code === 200) {
         this.categoryParentData = res.data
       } else {
         this.$message.error("获取父级分类列表失败！")
       }
     },
    async handleAddCategory (continueAddCategory) {
      this.$refs.addCategoryFrom.validate(valid => {
        if (!valid) {
          this.$message.error('存在错误内容，请完善信息！')
          return false
        } else {
          this.$confirm('确定添加该分类信息吗？', '提示',
              {
                'confirmButtonText': '确定',
                'cancelButtonText': '取消',
                'type': 'warning'
              }).then(async () => {
            let res = await AddCategoryApi(this.addCategoryParam);
            if (res.code === 200) {
              //刷新主界面，显示最新数据
              this.$parent.init()
              this.$message.success("添加分类成功")
              //更新初始数据
             this.resetFrom()
              //如果非继续添加，关闭添加窗口
              if (!continueAddCategory) {
                this.close()
              }
            } else {
              this.$message.error(res.msg)
            }
          }).catch((e) => {
            if (e === 'cancel') {
              this.$message.info('取消添加')
            } else {
              this.$message.error('未知错误！')
            }
          });
        }
      });
    }
  }

}
</script>
<style scoped lang="less">
.add-category {
  .el-dialog {
    .el-card {
      width: 70%;
      margin: 0 auto;

      .add-category-body {
        width: 80%;
        margin: 10px 20px;

        .add-category-input {
          width: 280px;
        }
      }
    }

    .dialog-footer {
      margin: 0 auto;
      padding: 20px 20px;
      max-width: 400px;
    }
  }
}

/deep/ .el-dialog {
  border-radius: 10px;
}

</style>
